package com.jams.goodox.net;

import android.content.Context;

import com.jams.goodox.utils.ToastUtil;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by jams on 2017/3/8.
 * ***
 * Tel: ***
 */

public class RetrofitHelper {
    private ArrayList<Call> calls = new ArrayList<>();

    public static RetrofitHelper get(Context context) {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        retrofitHelper.setContext(context);
        return retrofitHelper;
    }

    private RetrofitHelper() {}

    private Context context;

    private void setContext(Context context) {
        this.context = context;
    }

    public <T extends BaseEntity> void  enqueue(final Call<T> call, final RetrofitCallbackListener<T> callback) {
        calls.add(call);
        call.enqueue(new RetrofitCallBacks<T>(context) {
            @Override
            public void onSuccess(Response<T> response) {
                callback.onSuccess(call,response.body());
            }

            @Override
            public void onFail(String message) {
                callback.onError(message);//无数据或者请求失败
            }

            @Override
            public void unSuccessStatus(String status, String message) {
                if(callback == null){
                    return;
                }
                if(callback instanceof  RetrofitUnSuccessCallbackListener){
                    ToastUtil.dismiss();
                    ((RetrofitUnSuccessCallbackListener) callback).unSuccess(status,message);
                }else {
                    callback.onError(message);//如果不需要处理非100status的情况，则将非100的status也设置为失败
                }
            }
        });
    }



    /**
     * 取消所有请求
     */
    public void cancelCalls() {
        for (Call call : calls) {
            if (call != null && !call.isCanceled()) {
                call.cancel();
            }
        }
    }

}
